// routes/routes.go
package routes

import (
	"gorm_project/config"
	"gorm_project/controllers"
	"gorm_project/middleware"
	"gorm_project/repositories"
	"gorm_project/services"

	"github.com/gin-gonic/gin"
)

func SetupRouter(cfg *config.Config) *gin.Engine {
	router := gin.Default()

	// 初始化数据库
	db := config.GetDB()

	// 初始化仓库
	userRepo := repositories.NewUserRepository(db)
	articleRepo := repositories.NewArticleRepository(db)
	//categoryRepo := repositories.NewCategoryRepository(db)

	// 初始化服务
	authService := services.NewAuthService(userRepo, cfg.JWTSecret)
	articleService := services.NewArticleService(articleRepo)
	//categoryService := services.NewCategoryService(categoryRepo)

	// 初始化控制器
	authCtrl := controllers.NewAuthController(authService)
	articleCtrl := controllers.NewArticleController(articleService)
	//categoryCtrl := controllers.NewCategoryController(categoryService)

	// 中间件
	router.Use(middleware.CORSMiddleware())
	//router.Use(middleware.LoggerMiddleware())

	// 静态文件
	router.Static("/static", "./static")
	router.Static("/uploads", "./uploads")

	// API路由
	api := router.Group("/api/v1")
	{
		// 认证路由
		auth := api.Group("/auth")
		{
			auth.POST("/register", authCtrl.Register)
			auth.POST("/login", authCtrl.Login)
		}

		// 公开路由
		public := api.Group("/")
		{
			public.GET("/articles", articleCtrl.GetArticles)
			public.GET("/articles/:id", articleCtrl.GetArticle)
			//public.GET("/categories", categoryCtrl.GetCategories)
		}

		// 需要认证的路由
		authorized := api.Group("/")
		authorized.Use(middleware.AuthMiddleware(authService))
		{
			authorized.POST("/articles", articleCtrl.CreateArticle)
			//authorized.PUT("/articles/:id", articleCtrl.UpdateArticle)
			//authorized.DELETE("/articles/:id", articleCtrl.DeleteArticle)
		}

		// 管理员路由
		admin := api.Group("/admin")
		admin.Use(middleware.AuthMiddleware(authService))
		admin.Use(middleware.AdminMiddleware())
		{
			// 管理员专属接口
		}
	}

	return router
}
